<script setup lang="ts">
import {useCategoryStore} from "@/stores/modules/category.ts";
import {reqAttr, reqAddOrUpdateAttr, reqDeleteAttr} from "@/api/product/attr";
import type {AttrResponseData, AttrList, Attr, AttrObj} from "@/api/product/attr/type.ts";
import {nextTick, reactive, ref, watch, onBeforeUnmount} from "vue";
import {ElMessage} from "element-plus";

const categoryStore = useCategoryStore()

const attrArr = ref<AttrList>([])
// 卡片切换
const scene = ref<boolean>(true)

const inputArr = ref<any>([])

const attrParams = reactive<Attr>({
  attrName:'',
  attrValueList:[],
  categoryId:'',  // 3级分类的id
  categoryLevel:3 // 3级分类
})

watch(()=>categoryStore.C3Id, async ()=>{
  attrArr.value = []
  const {C1Id, C2Id, C3Id} = categoryStore
  if(C3Id) {
    const result: AttrResponseData = await reqAttr(C1Id, C2Id, C3Id)
    console.log("src/views/product/attr/index.vue", result)
    if (result.code === 200) {
      attrArr.value = result.data
    }
  }
})

const addAttr = () => {
  Object.assign(attrParams, {
    attrName:'',
    attrValueList:[],
    categoryId:categoryStore.C3Id,  // 3级分类的id
    categoryLevel:3 // 3级分类
  })
  scene.value = !scene.value
}

const updateAttr = (row:Attr) => {
  scene.value = !scene.value

  Object.assign(attrParams, JSON.parse(JSON.stringify(row)))
}

const deleteAttr = async (attrId:number) => {
  const result = await reqDeleteAttr(attrId)
  if(result.code === 200) {
    ElMessage({
      type:'success',
      message:'删除成功'
    })
    const result = await reqAttr(categoryStore.C1Id, categoryStore.C2Id, categoryStore.C3Id)
    if(result.code === 200) attrArr.value = result.data
  }else {
    ElMessage({
      type:'error',
      message:'删除失败'
    })
  }
}

const cancel = () => {
  attrParams.attrName = ''
  attrParams.attrValueList = []
  attrParams.categoryId = ''
  scene.value = !scene.value
}

// 添加属性值
const addAttrValue = () => {
  attrParams.attrValueList.push({
    valueName: '',
    flag:true
  })

  nextTick(()=>{
    inputArr.value[attrParams.attrValueList.length - 1].focus()
  })
}

const save = async () => {
  const result = await reqAddOrUpdateAttr(attrParams)
  console.log("src/views/product/attr/index.vue", result)
  if(result.code === 200) {
    scene.value = !scene.value
    ElMessage({
      type:'success',
      message:attrParams.id ? '修改成功' : '添加成功'
    })
    attrParams.attrName = ''
    attrParams.attrValueList = []
    attrParams.categoryId = ''
    const attr = await reqAttr(categoryStore.C1Id, categoryStore.C2Id, categoryStore.C3Id)
    if(attr.code === 200) {
      attrArr.value = attr.data
    }
  }else {
    ElMessage({
      type:'error',
      message:attrParams.id ? '修改失败' : '添加失败'
    })
  }
}

const toLook = (row:AttrObj, $index:number) => {
  if(row.valueName === '') {
    attrParams.attrValueList.splice($index, 1)
    ElMessage({
      type:'error',
      message:'输入不能为空'
    })
    return
  }
  let repeat = attrParams.attrValueList.find((item)=> {
    if(item != row) {
      return item.valueName === row.valueName
    }
  })

  if(repeat) {
    attrParams.attrValueList.splice($index, 1)
    ElMessage({
      type:'error',
      message:'属性值不能重复'
    })
    return
  }
  row.flag = false
}

const toEdit = (row:AttrObj, $index:number) => {
  row.flag = true
  nextTick(()=>{
    inputArr.value[$index].focus()
  })
}

onBeforeUnmount(()=>{
  categoryStore.$reset()
})
</script>

<template>
  <Category :scene="scene"/>
  <el-card style="margin: 10px 0;">
    <div v-show="scene">
      <el-button :disabled="categoryStore.C3Id === ''" type="primary" size="default" icon="Plus" @click="addAttr">添加属性</el-button>
      <el-table style="margin: 10px 0" :border="true" :data="attrArr">
        <el-table-column width="80px" label="序号" type="index" align="center"></el-table-column>
        <el-table-column width="120px" label="属性名称" align="center" prop="attrName"></el-table-column>
        <el-table-column label="属性值名称" align="center">
          <template v-slot="{row}">
            <el-tag style="margin: 5px" v-for="item in row.attrValueList" :key="item.id">{{item.valueName}}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="240px" align="center">
          <template v-slot="{row}">
            <el-button type="primary" size="small" icon="Edit" @click="updateAttr(row)"></el-button>
            <el-popconfirm :title="`你确定删除${row.attrName}吗`" width="200px" @confirm="deleteAttr(row.id)">
              <template v-slot:reference>
                <el-button type="primary" size="small" color="#c12127" icon="Delete"></el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div v-show="!scene">
      <el-form :inline="true">
        <el-form-item label="属性名称">
          <el-input placeholder="请输入属性名称" v-model="attrParams.attrName"></el-input>
        </el-form-item>
      </el-form>
      <el-button @click="addAttrValue" :disabled="!attrParams.attrName" type="primary" size="default" icon="Plus">添加属性值</el-button>
      <el-button @click="cancel" type="primary" size="default">取消</el-button>
      <el-table style="margin: 10px" border :data="attrParams.attrValueList">
        <el-table-column width="80px" type="index" align="center" label="序号"></el-table-column>
        <el-table-column label="属性值名称">
          <template v-slot="{row, $index}">
            <el-input :ref="(vc:any) => inputArr[$index] = vc" @blur="toLook(row, $index)" v-if="row.flag" placeholder="请输入属性值名称" v-model="row.valueName"></el-input>
            <div @click="toEdit(row, $index)" v-else>{{row.valueName}}</div>
          </template>
        </el-table-column>
        <el-table-column width="240px" label="属性值操作">
          <template v-slot="{$index}">
            <el-button type="primary" size="small" color="#c12127" icon="Delete" @click="attrParams.attrValueList.splice($index, 1)"></el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-button :disabled="!attrParams.attrValueList.length" type="primary" size="default" @click="save">保存</el-button>
      <el-button type="primary" size="default" @click="cancel">取消</el-button>
    </div>
  </el-card>
</template>

<style scoped lang="scss">

</style>